package com.apiinvoke;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

@Component
@Aspect
public class RequestLoggingAspect {

    private static final Logger LOGGER = LoggerFactory.getLogger(RequestLoggingAspect.class);

    @Autowired
    private HttpServletRequest request;

    @Pointcut("execution(* com.apiinvoke.controller..*(..))")
    public void controllerMethods() {}

    @Around("controllerMethods()")
    public Object logRequestAndResponse(ProceedingJoinPoint joinPoint) throws Throwable {
        String className = joinPoint.getTarget().getClass().getSimpleName();
        String methodName = joinPoint.getSignature().getName();
        LOGGER.info("Request: {} {} from {}", request.getMethod(), request.getRequestURI(), request.getRemoteAddr());
        LOGGER.info("Controller method called: {}.{}", className, methodName);
        LOGGER.info("Request parameters: {}", request.getParameterMap()); // optional, depending on your requirements

        long startTime = System.currentTimeMillis();
        Object result = joinPoint.proceed();
        long endTime = System.currentTimeMillis();

        LOGGER.info("Response: {} in {}ms", result.toString(), endTime - startTime);

        return result;
    }
}

